package com.ruitu.health_2.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health_2.R;
import com.ruitu.health_2.mvp.model.ProductModel;
import com.ruitu.health_2.mvp.presenter.ProductPresenter;
import com.ruitu.health_2.ui.adapter.EvaluateListAdapter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Router;
import com.ruitu.router_module.activity.PhotoCheckActivity;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.order.ConfirmOrder;
import com.ruitu.router_module.bean.product.Comment;
import com.ruitu.router_module.bean.product.ProDetail;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.bean.system.Common;
import com.ruitu.router_module.support.view.MyNestedScrollView;
import com.ruitu.router_module.support.widget.ProductSkuDialog;
import com.ruitu.router_module.util.GlideUtil;
import com.ruitu.router_module.util.ReqUtil;
import com.wuhenzhizao.sku.bean.SkuAttribute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import okhttp3.RequestBody;

public class ProductDetailActivity extends BaseActivity<ProductPresenter.ProDetailP, ProductModel.ProDetailM> {
    private ImageView iv_back, iv_share;
    private TextView tv_price, tv_name, tv_sub_title;// 价格 名称 介绍
    private RelativeLayout rl_title, rl_banner;// 标题栏布局,banner布局
    private View tab;// 标题栏tab
    private View divider1, divider2, divider3;
    private RelativeLayout rl_tab1, rl_tab2, rl_tab3;
    private MyNestedScrollView sv_content;// 整个滑动页面
    private ViewPager vp_banner;// 商品大图
    private VpBannerAdapter bannerAdapter;
    private RelativeLayout rl_evaluate;// 评价的整个布局
    private RecyclerView rcv_eva;// 评价列表
    private TextView tv_all_eva;// 查看评价
    private WebView webview;//用于显示商品详情
    private TextView tv_add_to_cart, tv_buy_now;// 加购物车,立即购买
    private RelativeLayout rl_service, rl_cart;// 客服,购物车
    private LinearLayout ll_collect;// 收藏
    private ImageView iv_collect;// 收藏的图标
    private TextView tv_collect, tv_model_num;// 收藏的文字,展示型号数量
    private LinearLayout ll_sel_model_num;// 选择规格型号数量

    private List<String> albumPicList = new ArrayList<>();// 商品轮播banner地址
    private List<Comment> evaluateList = new ArrayList<>();// 评价列表
    private EvaluateListAdapter evaListAdapter;// 评价列表adapter

    private String id;// 传过来的商品id
    private ProDetail detail;// 请求得到的商品详情对象
    private List<Sku> skuList = new ArrayList<>();// 请求的SkuList
    private ConfirmOrder confirmOrder;// 请求得到的立即购买数据

    private int SCREEN_WIDTH = 0;
    private String[] TITLES = {"商品", "评价", "详情"};

    private boolean isToCart = false;// 是否是加购物车 否直接购买
    private boolean isSelModelNum = false;// 是否是选择规格数量(是,弹出选择框,点确定只选择规格型号,不会进行加购或者购买)
    private int buyNum = 1;// 记录购买数量
    private String skuId = "";// 记录规格id
    private boolean isCollect = false;// 是否已经收藏
    private String collectId = "";// 收藏的id

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iv_back = findViewById(R.id.iv_back);
        iv_share = findViewById(R.id.iv_share);
        tv_price = findViewById(R.id.tv_price);
        tv_name = findViewById(R.id.tv_name);
        tv_sub_title = findViewById(R.id.tv_sub_title);
        rl_title = findViewById(R.id.rl_title);
        rl_banner = findViewById(R.id.rl_banner);
        tab = findViewById(R.id.tab);
        divider1 = findViewById(R.id.divider1);
        divider2 = findViewById(R.id.divider2);
        divider3 = findViewById(R.id.divider3);
        rl_tab1 = findViewById(R.id.rl_tab1);
        rl_tab2 = findViewById(R.id.rl_tab2);
        rl_tab3 = findViewById(R.id.rl_tab3);
        sv_content = findViewById(R.id.sv_content);
        vp_banner = findViewById(R.id.vp_banner);
        rl_evaluate = findViewById(R.id.rl_evaluate);
        rcv_eva = findViewById(R.id.rcv_eva);
        tv_all_eva = findViewById(R.id.tv_all_eva);
        webview = findViewById(R.id.webview);
        tv_add_to_cart = findViewById(R.id.tv_add_to_cart);
        tv_buy_now = findViewById(R.id.tv_buy_now);
        rl_service = findViewById(R.id.rl_service);
        rl_cart = findViewById(R.id.rl_cart);
        ll_collect = findViewById(R.id.ll_collect);
        iv_collect = findViewById(R.id.iv_collect);
        tv_collect = findViewById(R.id.tv_collect);
        ll_sel_model_num = findViewById(R.id.ll_sel_model_num);
        tv_model_num = findViewById(R.id.tv_model_num);

        rl_title.setAlpha(0);

        // 初始化tab
//        for (int i = 0; i < TITLES.length; i++) {
//            tab.addTab(tab.newTab().setText(TITLES[i]), i);
//        }
        // 初始化商品大图
        bannerAdapter = new VpBannerAdapter();
        vp_banner.setAdapter(bannerAdapter);
        // 初始化评价列表
        evaListAdapter = new EvaluateListAdapter(this);
        LinearLayoutManager evaMagager = new LinearLayoutManager(this);
        rcv_eva.setLayoutManager(evaMagager);
        rcv_eva.setAdapter(evaListAdapter);

        SCREEN_WIDTH = ScreenUtils.getScreenWidth();

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rl_banner.getLayoutParams();
        params.width = SCREEN_WIDTH;
        params.height = SCREEN_WIDTH;
        rl_banner.setLayoutParams(params);

        setListeners();

        try {
            id = getIntent().getStringExtra("id");
            p.reqProDetail(id);
            showProgress();
        } catch (Exception e) {
            e.printStackTrace();
            finish();
            ToastUtils.showShortSafe("数据异常,请重试");
        }
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {// 商品详情
            detail = (ProDetail) data;
            evaluateList = detail.getListComment();
            evaListAdapter.setDataList(evaluateList);
            if (isDataEmpty(evaluateList)) {
                tv_all_eva.setText("暂未收到评价");
            } else {
                tv_all_eva.setText("查看全部评价");
            }

            p.reqSkuList(id);// 商品详情请求成功后请求skuList

            albumPicList.clear();
            try {
                String[] picUrlArr = detail.getAlbumPics().split(",");
                for (String url : picUrlArr) {
                    albumPicList.add(url);
                }
                bannerAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }

            tv_price.setText("￥" + detail.getPrice());
            tv_name.setText(detail.getName());
            tv_sub_title.setText(detail.getSubTitle());

            String content = detail.getDetailMobileHtml();
            initWebview(content);
        }
        if (code == 2) {// 加入购物车
            if (isOk) {// 成功加入购物车
                dialog.dismiss();
                Arad.bus.post(new EventModel(19122300));
            } else {

            }
        }
        if (code == 3) {// 获取skuList
            skuList = (List<Sku>) data;
        }
        if (code == 4) {// 立即购买
            if (isOk) {
                dialog.dismiss();
                confirmOrder = (ConfirmOrder) data;
                Bundle bundle = new Bundle();
                bundle.putSerializable("order", confirmOrder);
                bundle.putString("status", "1");
                try {
                    Router.startActivity(this, "com.ruitu.health_1.ui.CommitOrderActivity", bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {

            }
        }
        if (code == 5) {// 添加收藏
            if (isOk) {
                isCollect = true;// 已经收藏
                Common common = (Common) data;
                collectId = common.getId();
            } else {
                isCollect = false;// 收藏失败
            }
            setCollectState();
        }
        if (code == 6) {// 取消收藏
            if (isOk) {
                isCollect = false;// 已经收藏
            } else {
                isCollect = true;// 收藏失败
            }
            setCollectState();
        }
    }

    private void setCollectState() {
        if (isCollect) {
            iv_collect.setImageResource(R.mipmap.ic_collect_3);
            tv_collect.setTextColor(getResources().getColor(R.color.text_red));
            tv_collect.setText("已收藏");
        } else {
            iv_collect.setImageResource(R.mipmap.ic_collect_1);
            tv_collect.setTextColor(getResources().getColor(R.color.text_dark_gray));
            tv_collect.setText("收藏");
        }
    }

    private void initWebview(String url) {
//        webview.getSettings().setJavaScriptEnabled(true);//开启js的支持
//        //自适应屏幕
////        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webview.getSettings().setUseWideViewPort(true);
//        webview.getSettings().setLoadWithOverviewMode(true);
//        webview.setHorizontalScrollBarEnabled(false);//水平不显示
//        webview.setVerticalScrollBarEnabled(false); //垂直不显示
//        webview.setWebViewClient(new WebViewClient() { //调用自身，不调用系统浏览器
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                if (TextUtils.isEmpty(url)) {
//                } else {
//                    if (url.startsWith("tmall://")) {
//
//                    } else {
//                        view.loadUrl(url);
//                    }
//                }
//                return true;
//            }
//        });
//        webview.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });
//        webview.setWebChromeClient(new WebChromeClient() {
//            public void onProgressChanged(WebView view, int progress) {
//                // Activity和Webview根据加载程度决定进度条的进度大小
//                // 当加载到100%的时候 进度条自动消失
//                if (progress == 100) {
//                }
//            }
//        });
//        webview.loadUrl(url);

        // 开启js支持
        webview.getSettings().setJavaScriptEnabled(true);
        //2、关闭自动适应
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(false);
        // 3、//重写WebViewClient中的onPageFinished方法
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //修改图片大小
                int screenWidth = ScreenUtils.getScreenWidth();
//                String width = String.valueOf(screenWidth - SizeUtils.dp2px(50));
//                String width2 = String.valueOf(screenWidth - SizeUtils.dp2px(10));
                String width2 = String.valueOf(SizeUtils.px2dp(screenWidth) - 15);

                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
//                        "myimg.margin = 0;" +
                        "if(myimg.width > " + width2 + "){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width =" + width2 + ";" +
                        "}" +
                        "}" +
                        "}";
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }
        });
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
//        webview.loadUrl(url);
        webview.loadData(url, "text/html;charset=utf-8", null); // 加载定义的代码，并设定编码格式和字符集。
    }

    private void setListeners() {
        setOnClickListener(iv_back, iv_share, tv_all_eva, tv_add_to_cart, tv_buy_now, rl_service
                , rl_cart, ll_collect, ll_sel_model_num, rl_tab1, rl_tab2, rl_tab3);
        sv_content.setScrollViewListener(new MyNestedScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyNestedScrollView scrollView, int x, int y, int oldx, int oldy) {
                float alpha = 0F;
                if (oldy > y && y < SizeUtils.dp2px(40)) {
                    alpha = 0F;
                } else {
                    alpha = ((float) y + SizeUtils.dp2px(40)) / SizeUtils.dp2px(200);
                }
                rl_title.setAlpha(alpha);

                if (detailY > 0) {
                    if (y >= detailY - SizeUtils.dp2px(70)) {
                        setCurrTab(3);// 详情指示器
                    } else if (y < evaluateY - SizeUtils.dp2px(70)) {
                        setCurrTab(1);// 商品指示器
                    } else {
                        setCurrTab(2);// 评价指示器
                    }
                }
            }
        });
//        tab.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
//            @Override
//            public void onTabSelected(XTabLayout.Tab tab) {
//                int index = tab.getPosition();
//                if (index == 0) {
//                    sv_content.scrollTo(0, 0);
//                } else if (index == 1) {
//                    sv_content.scrollTo(0, evaluateY - SizeUtils.dp2px(70));
//                } else {
//                    sv_content.scrollTo(0, detailY - SizeUtils.dp2px(70));
//                }
//            }
//        });
    }

    // 设置指示器
    private void setCurrTab(int index) {
        if (index == 1) {
            divider1.setVisibility(View.VISIBLE);
            divider2.setVisibility(View.INVISIBLE);
            divider3.setVisibility(View.INVISIBLE);
        } else if (index == 2) {
            divider1.setVisibility(View.INVISIBLE);
            divider2.setVisibility(View.VISIBLE);
            divider3.setVisibility(View.INVISIBLE);
        } else if (index == 3) {
            divider1.setVisibility(View.INVISIBLE);
            divider2.setVisibility(View.INVISIBLE);
            divider3.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_tab1) {
            sv_content.scrollTo(0, 0);
        }
        if (v == rl_tab2) {
            sv_content.scrollTo(0, evaluateY - SizeUtils.dp2px(70));
        }
        if (v == rl_tab3) {
            sv_content.scrollTo(0, detailY - SizeUtils.dp2px(70));
        }
        if (v == iv_back) {// 返回
            finish();
        }
        if (v == iv_share) {// 分享
            ToastUtils.showShortSafe("分享..敬请期待");
        }
        if (v == tv_all_eva) {
            if (!isDataEmpty(evaluateList)) {
                ToastUtils.showShortSafe(tv_all_eva.getText());
            }
        }
        if (v == ll_sel_model_num) {// 选择规格型号,数量
            isSelModelNum = true;
            showSkuDialog();
        }
        if (v == tv_add_to_cart || v == tv_buy_now) {// 加购物车 / 立即购买
            if (v == tv_add_to_cart) {
                isToCart = true;
            }
            if (v == tv_buy_now) {
                isToCart = false;
            }
            if (CommonUtils.isLoginToActivity(this)) {
                if (null == detail || isDataEmpty(skuList)) {
                    ToastUtils.showShortSafe("商品信息加载中");
                    return;
                }
                if (!TextUtils.isEmpty(skuId)) {// 说明已经选择了规格型号,不需要弹窗,直接加购物车或者购买
                    if (isToCart) {// 加购物车
                        reqAddToCart();
                    } else {// 直接购买
                        reqBuyNow();
                    }
                    return;
                }
                showSkuDialog();
                isSelModelNum = false;
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_service) {// 客服
            ToastUtils.showShortSafe("客服..敬请期待");
        }
        if (v == rl_cart) {
            if (CommonUtils.isLoginToActivity(this)) {
                try {
                    Router.startActivity(ProductDetailActivity.this, "com.ruitu.health_1.ui.CartActivity");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == ll_collect) {// 收藏
            if (CommonUtils.isLoginToActivity(this)) {
                Map<String, String> map = new HashMap<>();
                map.put("memberId", AppHolder.instance().getUser().getId());
                if (!isCollect) {
                    map.put("infoId", id);
                    map.put("type", "0");// 0:商品 1:文章 2:视频 3:艺人
                } else {
                    map.put("infoId", collectId);
                }
                RequestBody body = ReqUtil.getBody(map, true);
                if (isCollect) {
                    if (TextUtils.isEmpty(collectId)) {
                        ToastUtils.showShortSafe("数据有误,请稍后重试");
                    } else {
                        p.reqDelCollect(body);
                        hideProgress();
                        showProgressWithText(true, "收藏中..");
                    }
                } else {
                    p.reqAddCollect(body);
                    hideProgress();
                    showProgressWithText(true, "取消中..");
                }
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
    }

    private ProductSkuDialog dialog;

    private void showSkuDialog() {
        if (isDataEmpty(skuList)) {
            ToastUtils.showShortSafe("数据异常");
            return;
        }
        if (dialog == null) {
            dialog = new ProductSkuDialog(this);
            // 封装一个商品对象
            ProHome pro = new ProHome();
            if (!isDataEmpty(albumPicList)) {// 商品的几个大图
                pro.setPic(albumPicList.get(0));
            } else {
                pro.setPic("");
            }
            pro.setStock(detail.getStock());
            pro.setUnit(detail.getUnit());
            pro.setPrice(detail.getPrice());

            dialog.setData(pro, skuList, new ProductSkuDialog.Callback() {
                @Override
                public void onAdded(com.wuhenzhizao.sku.bean.Sku sku, int quantity) {
                    buyNum = quantity;
                    skuId = sku.getId();
                    if (isSelModelNum) {// 只是选择规格数量,需要显示sku信息
                        List<SkuAttribute> attributeList = sku.getAttributes();
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < attributeList.size(); i++) {
                            if (i != 0) {
                                builder.append(" ");
                            }
                            SkuAttribute attribute = attributeList.get(i);
//                            builder.append("\"" + attribute.getValue() + "\"");
                            builder.append(attribute.getValue());
                        }
                        tv_model_num.setText("已选:  \"" + builder.toString() + "\" ×" + quantity);
                        dialog.dismiss();
                    } else {
                        if (isToCart) {// 加购物车
                            reqAddToCart();
                        } else {// 直接购买
                            reqBuyNow();
                        }
                    }
                }
            });
        }
        dialog.show();
    }

    // 请求加购物车
    private void reqAddToCart() {
        Map<String, String> map = new HashMap<>();
        map.put("productId", detail.getId());
        map.put("memberId", AppHolder.instance().getUser().getId());
        map.put("productSkuId", skuId);
        map.put("quantity", "" + buyNum);
        RequestBody body = ReqUtil.getBody(map, true);
        p.reqAddToCart(body);
        hideProgress();
        showProgressWithText(true, "操作中..");
    }

    // 请求立即购买
    private void reqBuyNow() {
        String uId = AppHolder.instance().getUser().getId();
        String pId = id;
        String type = "0";// 0-普通商品，1-视频，2-健康订单
        p.reqBuyNow(uId, pId, type, skuId, buyNum + "");
        hideProgress();
        showProgressWithText(true, "操作中..");
    }

    private int detailY = 0;// 商品详情的y坐标
    private int evaluateY = 0;// 商品评价的y坐标

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            // webview
            int[] position = new int[2];
            webview.getLocationInWindow(position);
            detailY = position[1];

            // evaluateY
            int[] position2 = new int[2];
            rl_evaluate.getLocationInWindow(position2);
            evaluateY = position2[1];
        }
    }

    // 点击详情执行
    public void onDetailClick() {//详情
        try {
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    sv_content.scrollTo(0, detailY - SizeUtils.dp2px(0));
                }
            }, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class VpBannerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return albumPicList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView iv = new ImageView(ProductDetailActivity.this);
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

            GlideUtil.loadImg(albumPicList.get(position), iv);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetailActivity.this, PhotoCheckActivity.class);
                    intent.putExtra("position", position);
                    ArrayList<String> imgPaths = new ArrayList<>();
                    for (String i : albumPicList) {//封装图片路径,传到图片查看页面
                        imgPaths.add(i);
                    }
                    intent.putExtra("list", imgPaths);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
            });

            container.addView(iv);
            return iv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((ImageView) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}
